<template>
  <div class="mod-config">
    <div v-if="!addOrUpdateVisible">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input v-model="dataForm.title" placeholder="标题" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">查询</el-button>
          <el-button v-if="isAuth('admin:aboutus:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
          <el-button v-if="isAuth('admin:aboutus:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <!-- <el-table-column
          prop="aboutUsId"
          header-align="center"
          align="center"
          label="唯一标识">
        </el-table-column> -->
        <el-table-column
          prop="title"
          header-align="center"
          align="center"
          label="标题">
        </el-table-column>
        <el-table-column
          prop="companyName"
          header-align="center"
          align="center"
          label="单位名称">
        </el-table-column>
        <el-table-column
          prop="address"
          header-align="center"
          align="center"
          label="地址">
        </el-table-column>
        <el-table-column
          prop="imgs"
          header-align="center"
          align="center"
          label="缩略图">
           <template slot-scope="scope">
             <img :src="scope.row.imgs" width="100px" height="80px"/>
          </template>
        </el-table-column>
         
        <el-table-column
          prop="aboutUsNo"
          header-align="center"
          align="center"
          label="序号">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.aboutUsId)">修改</el-button>
            <el-button type="text" size="small" @click="deleteHandle(scope.row.aboutUsId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>


    
    <div v-if="addOrUpdateVisible">
      <el-form :model="editorDataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editorDataForm.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="单位名称" prop="companyName">
          <el-input v-model="editorDataForm.companyName" placeholder="单位名称"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editorDataForm.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" >
          <!-- <el-input v-model="editorDataForm.content" placeholder="内容"></el-input> -->
         <vue-wangeditor isRealtime=true ref="vueWangeditor" id="editor" :value="text" width='80%' :menus='menu' :uploadImgUrl='url' @load="editorUploadSuccess" @change="changeVchange"> </vue-wangeditor>
        </el-form-item>
        <el-form-item label="序号" prop="aboutUsNo">
          <el-input v-model="editorDataForm.aboutUsNo" placeholder="序号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dataFormSubmit()">保存</el-button>
          <el-button @click="addOrUpdateVisible = false">退出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 弹窗, 新增 / 修改 -->
    <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update> -->
  </div>
</template>

<script>
  
  import AddOrUpdate from './aboutus-add-or-update'
  import vueWangeditor from 'vue-wangeditor'
  export default {
    data () {
      return {
        dataForm: {
          title: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        text: '' ,
        url: '',
        imageUrl: '',
        dialogVisible: false,

        editorDataForm: {
          aboutUsId: 0,
          title: '',
          companyName: '',
          address: '',
          imgs: '',
          content: '',
          aboutUsNo: ''
        },
        dataRule: {
          title: [
            { required: true, message: '标题不能为空', trigger: 'blur' }
          ],
          companyName: [
            { required: true, message: '单位名称不能为空', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '地址不能为空', trigger: 'blur' }
          ],
          imgs: [
            { required: true, message: '缩略图地址不能为空', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '内容不能为空', trigger: 'blur' }
          ],
          aboutUsNo: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ]
        },
        menu:[
          'source',	// 源码模式
          '|',
          'bold',	// 粗体
          'underline',	// 下划线
          'italic',	// 斜体
          'strikethrough',	// 中线
          'eraser',	// 清空格式
          'forecolor',	// 文字颜色
          'bgcolor',	// 背景颜色
          '|',
          'quote',	// 引用
          'fontfamily',	// 字体
          'fontsize',	// 字号
          'head',	// 标题
          'unorderlist',	// 无序列表
          'orderlist',	// 有序列表
          'alignleft',	// 左对齐
          'aligncenter',	// 居中
          'alignright',	// 右对齐
          '|',
          'link',	// 链接
          'unlink',	// 取消链接
          'table',	// 表格
          'emotion',	// 表情
          '|',
          'img',	// 图片
          //'video',	// 视频
          //'location',	// 位置
          'insertcode',	// 插入代码
          '|',
          'undo',	// 撤销
          'redo',	// 重做
          //'fullscreen'	// 全屏
        ],

      }
    },
    components: {
      AddOrUpdate,vueWangeditor
    },
    activated () {
      this.getDataList()
    },
    mounted () {
     
    },
    methods: {
      
     
      // 新增修改 回显
      init (id) {
        this.imageUrl=""
        this.text=""
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.editorDataForm.aboutUsId = id || 0
        if( !this.editorDataForm.aboutUsId){
          this.editorDataForm = {
          aboutUsId: 0,
          title: '',
          companyName: '',
          address: '',
          imgs: '',
          content: '',
          aboutUsNo: ''
        }
        }
        this.visible = true
        this.$nextTick(() => {
          
          this.$refs['dataForm'].resetFields()
          
          if (this.editorDataForm.aboutUsId) {
            this.$http({
              url: this.$http.adornUrl(`/admin/aboutus/info/${this.editorDataForm.aboutUsId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.editorDataForm.title = data.aboutUs.title
                this.editorDataForm.companyName = data.aboutUs.companyName
                this.editorDataForm.address = data.aboutUs.address
                this.editorDataForm.imgs = data.aboutUs.imgs
                this.imageUrl = data.aboutUs.imgs
                // this.editorDataForm.content = data.aboutUs.content
                this.text = data.aboutUs.content
                this.editorDataForm.aboutUsNo = data.aboutUs.aboutUsNo
              }
            })
          }
        })
      },
      // 上传图片
      handleAvatarSuccess (res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        if (res && res.code === 0) {
          if (this.num === this.successNum) {
            this.$message.success('上传成功')
            this.editorDataForm.imgs = res.url
          }
        } else {
          this.$message.error(res.msg)
        }
      },
      beforeAvatarUpload (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
      },
      //新增修改提交
      dataFormSubmit () {
        // this.addOrUpdateVisible = false
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/admin/aboutus/${!this.editorDataForm.aboutUsId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'aboutUsId': this.editorDataForm.aboutUsId || undefined,
                'title': this.editorDataForm.title,
                'companyName': this.editorDataForm.companyName,
                'address': this.editorDataForm.address,
                'imgs': this.editorDataForm.imgs,
                'content': this.editorDataForm.content,
                'aboutUsNo': this.editorDataForm.aboutUsNo
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                 this.addOrUpdateVisible = false
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/admin/aboutus/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'title': this.dataForm.title
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        
        this.addOrUpdateVisible = true
        this.init(id)
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.aboutUsId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/admin/aboutus/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
  // 
    editorUploadSuccess(OriginalName,resultText ){
     // debugger;
      console.log(resultText) 
      this.$refs.vueWangeditor.insertImg(JSON.parse(resultText).url); 
    },
    changeVchange(){
     
      this.editorDataForm.content= this.$refs.vueWangeditor.getHtml();
    }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>